# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def levelOrder(self, root):
        if root is None:
            return []
        ans = []
        q = []
        q.append(root)
        while len(q) > 0:
            k = len(q)
            tmp = []
            while k > 0:
                a = q[len(q) - 1]
                q.pop()
                # print(a)
                tmp.append(a.val)
                if a.left:
                    q.insert(0, a.left)
                if a.right:
                    q.insert(0, a.right)
                k -= 1
            ans.append(tmp)
        return ans
